package com.br.negocio.dao;

import java.util.Collections;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.br.negocio.vo.ModeloVO;

@Service("modeloDAO")
public class ModeloDAO {

	@PersistenceContext
	private EntityManager entityManager;

	@Transactional(propagation = Propagation.REQUIRED)
	public void inserirModelo(ModeloVO modeloVO) {
		try {
			entityManager.persist(modeloVO);
		} catch (Exception e) {
			throw new RuntimeException("Erro ao inserir modelo: " + e.getMessage(), e);
		}
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	public void atualizarModelo(ModeloVO modeloVO) {
		try {
			entityManager.merge(modeloVO);
		} catch (Exception e) {
			throw new RuntimeException("Erro ao atualizar modelo: " + e.getMessage(), e);
		}
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void removerModelo(ModeloVO modeloVO) {
		try {
			if (!entityManager.contains(modeloVO)) {
				modeloVO = entityManager.merge(modeloVO);
			}
			entityManager.remove(modeloVO);
		} catch (Exception e) {
			throw new RuntimeException("Erro ao remover modelo: " + e.getMessage(), e);
		}
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public ModeloVO obterModelo(ModeloVO modeloVO) {
		try {
			return entityManager.find(ModeloVO.class, modeloVO.getCodigo());
		} catch (Exception e) {
			throw new RuntimeException("Erro ao buscar modelo: " + e.getMessage(), e);
		}
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRED)
	public List<ModeloVO> obterListaModelo() {
		try {
			List<ModeloVO> lista = (List<ModeloVO>) entityManager.createNamedQuery("loadAllModelo").getResultList();
			if ((lista != null) && (!lista.isEmpty())) {
				return lista;
			} else {
				return Collections.EMPTY_LIST;
			}
		} catch (Exception e) {
			throw new RuntimeException("Erro ao carregar todos os modelos.", e);
		}
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean validaDuplicado(ModeloVO modeloVO) {
		Query query = entityManager.createNamedQuery("findDuplicatedModelo");
		query.setParameter("descricao", modeloVO.getDescricao());
		query.setParameter("cod_marca", modeloVO.getMarcaVO().getCodigo());
		List<ModeloVO> lista = query.getResultList();
		if (lista.isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

}